package onenet

import (
	"encoding/json"
	"io/ioutil"
	"net/http"

	"gitee.com/injoyai/goutil/g"
	https "gitee.com/injoyai/goutil/net/http"
)

// Option 选项
type Option struct {
	Http   *https.Client
	FnBack func(*Back) error
}

//回调处理
func (this *Option) handler(w http.ResponseWriter, r *http.Request) {
	result := func(w http.ResponseWriter, code int, v string) {
		w.WriteHeader(code)
		w.Write([]byte(v))
	}
	msg := r.URL.Query().Get("msg")
	if this.FnBack != nil {
		bs, err := ioutil.ReadAll(r.Body)
		if err != nil {
			result(w, 500, err.Error())
			return
		}
		if len(bs) != 0 {
			data := new(Back)
			if err := json.Unmarshal(bs, data); err != nil {
				result(w, 500, err.Error())
				return
			}
			if err := this.FnBack(data); err != nil {
				result(w, 500, err.Error())
				return
			}
		}
	}
	result(w, 200, msg)
}

//获取设备详情
func (this *Option) get(pid string) (Device, error) {
	type res struct {
		Respose
		Data Device `json:"data"`
	}
	data := new(res)
	if err := this.Http.Url("http://api.heclouds.com/devices/" + pid).Body(data).Get().Err(); err != nil {
		return Device{}, err
	}
	return data.Data, data.Err()
}

//注册设备
//imsi可以和imei一样
func (this *Option) create(imei, imsi string) (string, error) {
	req := newRegistDeviceReq(imei, imsi)
	type res struct {
		Respose
		Data RegistDeviceRes `json:"data"`
	}
	data := new(res)
	if err := this.Http.Url("http://api.heclouds.com/devices").Body(req).Bind(data).Post().Err(); err != nil {
		return "", err
	}
	return data.Data.DeviceID, data.Err()
}

//删除设备
func (this *Option) delete(pid string) error {
	data := new(Respose)
	if err := this.Http.Url("https://api.heclouds.com/devices/" + pid).Bind(data).Delete().Err(); err != nil {
		return err
	}
	return data.Err()
}

//设备通讯
func (this *Option) send(imei, order string) error {
	req := g.Map{"args": order}
	param := g.Map{
		"imei":        imei,
		"obj_id":      3200,
		"obj_inst_id": 0,
		"res_id":      5505,
		"timeout":     30,
	}
	data := new(Respose)
	if err := this.Http.Url("https://api.heclouds.com/nbiot/execute").SetQueryMap(param).Body(req).Bind(data).Post().Err(); err != nil {
		return err
	}
	return data.Err()
}
